;( function () {
    "use strict";
   	var param_map = Result.getLocationParamObject();
    var game_id = param_map.game_id;
    var quCode = null;
    var pageSize = 10;
    var pageNo = 1;
    var global_param_map;
    
	 $( function () {
		App.init();
		$("#head_login_status").empty();
		if(!App.checkLogin()){
			global_param_map = {};
			$("#head_login_status").append($("#un_login_template"));
		} else {
			global_param_map = App.getCookeData();
			$("#_user_name").html(global_param_map["nickname"]);
			if(global_param_map["user_icon"] !== undefined && global_param_map["user_icon"] != null 
					&& global_param_map["user_icon"] != ""){
					$("#_head_pic").attr("src", Interface.image.pre + global_param_map["user_icon"]);
				}
			$("#head_login_status").append($("#already_login_template"));
		}
		 
		 loadByIp();
		 //定位的
		 var cityJson = App.getCity();
		 if(cityJson){
			 $("#local_city").attr("org_code", cityJson.org_code);
			 $("#local_city").attr("org_name", cityJson.org_name);
			 $("#local_city").find("a").html(cityJson.org_name);
			 $("#local_city").removeClass("yes").addClass("yes");
		 } else {
			 $("#local_city").find("a").html("没定位到城市");
			 $("#local_city").removeClass("yes");
		 }
		 //用户正在用的cit
		 var useCityJson = App.getUseCity();
		 if(useCityJson){
			 quCode = useCityJson.org_code;
			 $("#chengshi").html(useCityJson.org_name);
		 }
		 loadAllCity();
		 if(useCityJson){
			 $(".citylist li.yes").removeClass("active");
			 var len = $(".citylist").find("li[org_code="+quCode+"]").length;
			 if(len == 1){
				 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
			 } else if (len > 1) {
				 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
			 }
		 }
		 
		 
		 $("#game_name").html(param_map.game_name);
		 loadDetail();
		 loadCommentList();
		 
		 $("#pinglun_pop").click(function(){
			 //判断用户是否登录。登录才能评论
			 if(global_param_map['id'] == undefined || global_param_map['id'] == null 
		     			|| global_param_map['id'] == ''){
				 alert("您还未登录");
				 return;
			 }
			 $('#comment-modal').modal({'closeViaDimmer':0,'width':760,'height':'488'});
			 $(".mark_star").each(function (indexstar, itemstar) {
		        $(itemstar).find(".icon-star").each(function (index, item) {
		            $(item).on("click", function () {
		                $(itemstar).find(".icon-star").removeClass("cur");
		                for (var i = 0; i <= index; i++) {
		                    $(itemstar).find(".icon-star").eq(i).addClass("cur");
		                }
		            });
		        });
		     });
		 });
		 
	 });
	 
	 
	 $("body").on("click", ".popquxiao", function(){
		 $("#input_content").val("");
		 $(".mark_star").html('<i class="icon-star"></i><i class="icon-star"></i><i class="icon-star"></i><i class="icon-star"></i><i class="icon-star"></i>');
	 });

	 $("body").on("click", ".tijiapinglun", function(){
		 if(global_param_map['id'] == undefined || global_param_map['id'] == null 
	     			|| global_param_map['id'] == ''){
			 alert("您还未登录");
			 return;
		 }
		 var ping = $("#input_content").val();
		 if(ping == null || ping == ""){
			 alert("请填写评论");
			 return false;
		 }
		 var starNum = $(".mark_star i.cur").length;
		 var params = {
			"userId" : global_param_map['id'], 
			"gameId" : game_id,
			"gameScore" : starNum,
			"content" : ping
		 };
		 Result.doResult( {
			 url:   Interface.zs.gameSubmitComment,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 alert("评论成功");
			 $('#comment-modal').modal('close');
			 $("#input_content").val("");
			 $(".mark_star").html('<i class="icon-star"></i><i class="icon-star"></i><i class="icon-star"></i><i class="icon-star"></i><i class="icon-star"></i>');
			 pageNo = 1;
			 loadCommentList();
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		
	 });
	 
	 
	 
	 function loadDetail(){
		 var prams = {"id" : game_id,};
		 if(global_param_map['id'] !== undefined && global_param_map['id'] != null 
	     			&& global_param_map['id'] != ''){
			 prams['userId'] = global_param_map['id'];
		 }
		 Result.doResult( {
			 url:  Interface.zs. gameGetGameDetailById,
			 data: prams,
			 type: "POST",
		 }, function ( data ) {
			 Result.fillData( $("#game_detail"), data, "field" );
			 $("#go").click(function(){
				 var game_url = $(this).attr("game_url");
				 window.open(game_url);
				 //window.location.href=game_url;
			 });
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 function loadCommentList(){
		 var $list = $("#comment_list"),
		 	$template = $("#comment_template");
		 var params= {"id" : game_id, "cPage" : pageNo, "pSize" : 5, "userId" : (global_param_map['id'] !== undefined && global_param_map['id'] != null 
	      			&& global_param_map['id'] != '') ? global_param_map['id'] : 0};
		 Result.doResult( {
			 url:  Interface.zs.gameQryGameCommentsInfo,
			 data: params,
			 type: "POST",
		 }, function ( data ) {
			 $("#ping_total").html(data.totalRow);
			 if(data.totalRow == 0){
				 $("#nono_comment").removeClass("am-hide");
			 } else {
				 $("#nono_comment").removeClass("am-hide").addClass("am-hide");
			 }
			 var dataList = data.list;
			 $list.empty();
			 if( $.isArray( dataList ) ) {
          		for( var i = 0, l = dataList.length; i < l; i++ ) {
          			var obj = $template.clone().removeAttr( "id" );
          			$list.append( Result.fillData( obj, dataList[i], "field" ));
                 }
              }
			 pageNo ++;
			 if(data.totalRow > 5){
				 $("#query_more_cpmment").show();
				 $("#query_more_cpmment").click(function(){
					 loadCommentList1();
				 });
			 }
			 
			 
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	
	 
	 function loadCommentList1(){
		 var $list = $("#comment_list"),
		 	$template = $("#comment_template");
		 var params= {"id" : game_id, "cPage" : pageNo, "pSize" : 5, "userId" : (global_param_map['id'] !== undefined && global_param_map['id'] != null 
	      			&& global_param_map['id'] != '') ? global_param_map['id'] : 0};
		 Result.doResult( {
			 url:  Interface.zs.gameQryGameCommentsInfo,
			 data: params,
			 type: "POST",
		 }, function ( data ) {
			 var dataList = data.list;
			 if(dataList.length == 0){
				 $("#query_more_cpmment").hide();
				 $("#query_more_cpmment").off();
				 return;
			 }
			 pageNo ++;
			 if( $.isArray( dataList ) ) {
          		for( var i = 0, l = dataList.length; i < l; i++ ) {
          			var obj = $template.clone().removeAttr( "id" );
          			$list.append( Result.fillData( obj, dataList[i], "field" ));
                 }
              }
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
	 }
	 
	 //todo 点赞评论
	 $("#comment_list").on("click", ".icon-zan", function(){
		 if(global_param_map['id'] == undefined || global_param_map['id'] == null 
	     			|| global_param_map['id'] == ''){
			 alert("您还未登录");
			 return;
		 }
		 if($(this).hasClass("cur")){
			 alert("您已经点赞过了");
			 return;
		 }
		 var that = $(this);
		 var comment_id = $(this).attr("comment_id");
		 var params= {
		     "userId" : global_param_map['id'],
		     "commentId" : comment_id,
		 };
		 Result.doResult( {
			 url:  Interface.zs.gameUpVote,
			 data: params,
			 type: "POST",
			 async: false,
		 }, function ( data ) {
			 alert("点赞成功!");
			 that.addClass("cur");
			 var src= that.parent().find(".numsss").text();
			 that.parent().find(".numsss").html(parseInt(src) + 1);
		 }, function ( desc ) {
	       Result.alert( "对不起:" + desc );
		 }, function ( err ) {
			 Result.alert( "错误:" + JSON.stringify(err));
		 } );
		 
	 });
	 
	 
	 $("#city-modal").on("focus", "#search_city", function(){
		 var that = $(this);
		 Result.doResult( {
	    	url: Interface.zs.orgGetOrgList,
	       	type: "POST",
	       	async: false,
	       	data : {}
	   	}, function ( data) {
	   		that.autocomplete(data , {  
	   			minChars: 0,
	   	        width: 680,
	   	        autoFill: false,
	            matchContains: true,  
	            highlight : false,
	            scroll : true, // 当结果集大于默认高度时是否使用卷轴显示  
	            formatItem: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatMatch: function(row, i, max) {  
	                 return row.org_name;  
	            },  
	            formatResult: function(row) {
	                return row.org_name;  
	            }  
	        }).result(function(event, row, formatted) {
	        	$(".citylist li.yes").removeClass("active");
	        	quCode = row.org_code;
            	var org_name = row.org_name;
				$("#chengshi").html(org_name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : org_name};
  			  	App.setUseCity(jj);
				var len = $(".citylist").find("li[org_code="+quCode+"]").length;
				 if(len == 1){
					 $(".citylist li.yes[org_code='"+quCode+"']").removeClass("active").addClass("active");
				 } else if (len > 1) {
					 $(".citylist li.yes[org_code='"+quCode+"']").eq(0).removeClass("active").addClass("active");
				 }
            });  
	   	}, function ( desc ) {
	        Result.alert( "对不起:" + desc );
	    }, function ( err ) {
	        Result.alert( "错误:" + JSON.stringify(err));
	    } );
	 });
	 
	 
	 
	 function loadAllCity(){
		var $list = $("#all_city_list"),
			$template = $("#all_city_template");
			$("#host_city").empty();
		Result.doResult( {
        	url: Interface.zs.orgGetOrgList,
           	type: "POST",
           	async: false,
           	data : {}
       	}, function ( data) {
	       	var letterMap = {
	       		"A" : [], "B" : [], "C" : [], "D" :[],  "E" : [], "F" : [], "G" : [], "H" : [],
	       		"I" : [], "J" : [], "K" : [], "L" : [], "M" : [], "N" : [], "O" : [],
	       		"P" : [], "Q" : [], "R" : [], "S" : [], "T" : [], "U" : [], "V" : [],
	       		"W" : [], "X" : [], "Y" : [], "Z" : []
	       	};
	       	if( $.isArray( data ) ) {
	    		for( var i = 0, l = data.length; i < l; i++ ) {
	    			var temp = data[i]["first_letter"].toUpperCase();
	    			letterMap[temp].push(data[i]);
	            }
	    	   for(var i in letterMap){
	    		  var letterList = letterMap[i];
	    		  if(letterList.length == 0){
	    			  continue;
	    		  }
	    		  var obj = $template.clone().removeAttr( "id" );
	    		  obj.find(".letter_fist").html(i);
	    		  obj.find(".citylist").empty();
	    		  for( var j = 0, l = letterList.length; j < l; j++ ) {
	    			  var org_name = letterList[j]['org_name'];
	    			  //填补hot
	    			  if(letterList[j]['is_hot'] == 1){
	    				  var ah = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
		    			  	+org_name+'</a></li>';
	    				  $("#host_city").append(ah);
	    			  }
	    			  
	    			  //当定位没有订到的话，默认一个已开通的城市
	    			  var active = "";
	    			  if(quCode == null || quCode == ""){
	    				  $("#chengshi").html(org_name);
		    			  quCode = letterList[j]['org_code'];
		    			  active = "active";
		    			  //设置默认的缓存
		    			  var jj = {"org_code" : quCode, "org_name" : org_name};
		    			  App.setUseCity(jj);
		    		  }
	    			  var a = '<li class="yes '+active+'" org_code="'+letterList[j]['org_code']+'" org_name="'+org_name+'"><a >'
	    			  	+org_name+'</a></li>';
	    			  obj.find(".citylist").append(a);
	    			  
		          }
	    		  $list.append(obj);
	    	   }
	        }
	       	
	        $(".citylist li.yes").off().click(function(){
		       	 $(".citylist li.yes").removeClass("active");
		       	 $(this).addClass("active");
	        });
	       	
			$("#btn-city-center").on("click",function(){
				var active =  $(".citylist li.active"),
					name = active.attr("org_name"),
					code = active.attr("org_code");
				quCode = code;
				$("#chengshi").html(name);
				$("#city-modal").modal("close");
				//选择完更新缓存
				var jj = {"org_code" : quCode, "org_name" : name};
  			  	App.setUseCity(jj);
			});
	       	
       	}, function ( desc ) {
            Result.alert( "对不起:" + desc );
        }, function ( err ) {
            Result.alert( "错误:" + JSON.stringify(err));
        } );
	 }
	 
	 
	 
	 window.replaceScore = function ( $field, score, rowVal ) {
		 var str = "";
		 if(score < 1){
			 str = '<i class="star-ban"></i><i class="star-none"></i><i class="star-none"></i><i class="star-none"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score == 1){
			 str = '<i class="star-all"></i><i class="star-none"></i><i class="star-none"></i><i class="star-none"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score > 1 && score < 2){
			 str = '<i class="star-all"></i><i class="star-ban"></i><i class="star-none"></i><i class="star-none"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score == 2){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-none"></i><i class="star-none"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score > 2 && score < 3){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-ban"></i><i class="star-none"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score == 3){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-none"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score > 3 && score < 4){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-ban"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score == 4){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-none"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score > 4 && score < 5){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-ban"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 } else if (score == 5){
			 str = '<i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-all"></i><i class="star-all"></i>' +
			 '<span class="font18 font-color-1 am-margin-left-xs am-fl">'+score+'分</span>';
		 }
		 $field.html(str);
	 };
	 
	
	 window.replaceLogo = function ( $field, logo, rowVal ) {
		$field.attr("src", Interface.image.pre + logo);
	 };
	 
	 window.replaceLogo1 = function ( $field, logo, rowVal ) {
		 if(logo == null || logo == ""){
			 $field.attr("src", "");
			 $field.hide();
		 } else {
			 $field.attr("src", Interface.image.pre + logo);
		 }
		
	 };
	 
	 window.replaceSelfUpvote = function ( $field, vote, rowVal ) {
		 if(rowVal['is_self_upvote'] > 0){
			 $field.addClass("cur");
		 } else {
			 $field.removeClass("cur");
		 }
		 $field.attr("comment_id", rowVal['id']);
	 };
	 
	 window.replace_game_url = function ( $field, game_url, rowVal ) {
			$field.attr("game_url", game_url);
		 };
		 
	
}( window ) );
